from django.db import models


# Create your models here.
class Category(models.Model):
    name = models.CharField(max_length=100, verbose_name="名字")

    def __str__(self):
        return self.name

    def to_dict(self, expand=False):
        d = dict()
        d["id"] = self.pk
        d["name"] = self.name
        if expand:
            d["sales_cell"] = [cell.to_dict() for cell in self.salescell_set.all()]
        return d


class SalesCell(models.Model):
    name = models.CharField(max_length=100, verbose_name="名字")
    category = models.ForeignKey(Category, verbose_name="品类")
    price = models.FloatField(verbose_name="价格")
    ico = models.ImageField(upload_to="order/ico", verbose_name="图例")

    def __str__(self):
        return self.name

    def to_dict(self):
        d = dict()
        d["id"] = self.pk
        d["name"] = self.name
        d["category"] = self.category.pk
        d["price"] = self.price
        d["ico"] = self.ico.url
        return d


class Order(models.Model):
    order_status_enum = ((1, "下单成功"), (2, "正在处理"), (3, "订单结束"))

    seat = models.CharField(max_length=100, verbose_name="座位号")
    created_time = models.DateTimeField(auto_now_add=True, verbose_name="下单时间")
    order_number = models.CharField(max_length=100, verbose_name="订单号")
    status = models.IntegerField(choices=order_status_enum, verbose_name="订单状态")

    def __str__(self):
        return self.order_number


class OrderDetails(models.Model):
    order = models.ForeignKey(Order, verbose_name="订单号")
    sales_cell = models.ForeignKey(SalesCell, verbose_name="餐品")
    nums = models.PositiveIntegerField(verbose_name="数量")
    completed_nums = models.PositiveIntegerField(default=0, verbose_name="已出餐数量")
    status = models.IntegerField(choices=Order.order_status_enum, default=1, verbose_name="订单状态")

    def __str__(self):
        return "{}:{}*{} ({})".format(self.order.created_time.strftime("%Y-%m-%d %H:%M:%S"), self.sales_cell, self.nums,
                                      self.order.order_number)

    def total_price(self):
        return self.sales_cell.price * self.nums

    def to_dict(self):
        d = dict()
        d["name"] = self.sales_cell.name
        d["order"] = self.order.order_number
        d["created_time"] = self.order.created_time
        return d
